﻿using Unity.Mathematics;
using UnityEngine;


public class DynamicObstacle : MonoBehaviour
{
    [Header("Obstacle Settings")]
    public float obstacleRadius = 1f;
    public float updateThreshold = 0.1f;
    public bool debugPositionChanges = false;
    
    private Vector3 lastPosition;
    private bool isRegistered;
    private int2 lastGridPosition;

    public float Radius => obstacleRadius;

    private void Start()
    {
        lastPosition = transform.position;
        lastGridPosition = DynamicObstacleManager.Instance != null ? 
            DynamicObstacleManager.Instance.flowField.WorldToGridPosition(lastPosition) : 
            int2.zero;
        
        RegisterObstacle();
    }

    private void Update()
    {
        if (DynamicObstacleManager.Instance == null) return;
        
        var currentGridPosition = DynamicObstacleManager.Instance.flowField.WorldToGridPosition(transform.position);
        
        bool positionChanged = Vector3.Distance(transform.position, lastPosition) > updateThreshold;
        bool gridPositionChanged = currentGridPosition.x != lastGridPosition.x || currentGridPosition.y != lastGridPosition.y;
        
        if (positionChanged || gridPositionChanged)
        {
            if (debugPositionChanges)
            {
                Debug.Log($"Obstacle moved: {name}\n" +
                          $"Old position: {lastPosition}, New position: {transform.position}\n" +
                          $"Old grid: {lastGridPosition}, New grid: {currentGridPosition}");
            }
            
            if (DynamicObstacleManager.Instance != null && isRegistered)
            {
                DynamicObstacleManager.Instance.UpdateObstaclePosition(this, lastPosition);
            }
            
            lastPosition = transform.position;
            lastGridPosition = currentGridPosition;
        }
    }

    private void OnDestroy()
    {
        UnregisterObstacle();
    }

    private void RegisterObstacle()
    {
        if (DynamicObstacleManager.Instance != null && !isRegistered)
        {
            DynamicObstacleManager.Instance.RegisterObstacle(this);
            isRegistered = true;
            
            if (debugPositionChanges)
            {
                Debug.Log($"Obstacle registered: {name}");
            }
        }
    }

    private void UnregisterObstacle()
    {
        if (DynamicObstacleManager.Instance != null && isRegistered)
        {
            DynamicObstacleManager.Instance.UnregisterObstacle(this);
            isRegistered = false;
            
            if (debugPositionChanges)
            {
                Debug.Log($"Obstacle unregistered: {name}");
            }
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = new Color(1, 0.5f, 0, 0.5f);
        Gizmos.DrawWireSphere(transform.position, obstacleRadius);
    }
}